//You are given an array of integers nums, there is a sliding window of size k w
//hich is moving from the very left of the array to the very right. You can only s
//ee the k numbers in the window. Each time the sliding window moves right by one 
//position. 
//
// Return the max sliding window. 
//
// 
// Example 1: 
//
// 
//Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
//Output: [3,3,5,5,6,7]
//Explanation: 
//Window position                Max
//---------------               -----
//[1  3  -1] -3  5  3  6  7       3
// 1 [3  -1  -3] 5  3  6  7       3
// 1  3 [-1  -3  5] 3  6  7       5
// 1  3  -1 [-3  5  3] 6  7       5
// 1  3  -1  -3 [5  3  6] 7       6
// 1  3  -1  -3  5 [3  6  7]      7
// 
//
// Example 2: 
//
// 
//Input: nums = [1], k = 1
//Output: [1]
// 
//
// Example 3: 
//
// 
//Input: nums = [1,-1], k = 1
//Output: [1,-1]
// 
//
// Example 4: 
//
// 
//Input: nums = [9,11], k = 2
//Output: [11]
// 
//
// Example 5: 
//
// 
//Input: nums = [4,-2], k = 2
//Output: [4]
// 
//
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 105 
// -104 <= nums[i] <= 104 
// 1 <= k <= nums.length 
// 
// Related Topics 堆 Sliding Window 
// 👍 974 👎 0


package leetcode.editor.cn;

import java.util.ArrayDeque;
import java.util.Deque;

//Java：Sliding Window Maximum
class P239SlidingWindowMaximum {
    public static void main(String[] args) {
        Solution solution = new P239SlidingWindowMaximum().new Solution();
        // TO TEST
        solution.maxSlidingWindow(new int[]{-7,-8,7,5,7,1,6,0}, 4);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.length == 0) {
                return null;
            }
            int len = nums.length < k ? 1 : nums.length - k + 1;
            int[] result = new int[len];
            Deque<Integer> maxQueue = new ArrayDeque<>();
            int maxIndex = 0;
            for (int i = 0; i < nums.length; i++) {
                int num = nums[i];
                if (i - k + 1 < 0) {
                    while (!maxQueue.isEmpty() && num > maxQueue.peekLast()) {
                        maxQueue.pollLast();
                    }
                    maxQueue.offerLast(num);
                } else {
                    while (!maxQueue.isEmpty() && num > maxQueue.peekLast()) {
                        maxQueue.pollLast();
                    }
                    maxQueue.offerLast(num);
                    result[maxIndex++] = maxQueue.peekFirst();
                    if (!maxQueue.isEmpty() && maxQueue.peekFirst() == nums[i - k + 1]) {
                        maxQueue.pollFirst();
                    }
                }


            }
            return result;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}